package com.sevennotes.classtable.utils

import android.content.Context
import android.net.Uri
import com.sevennotes.classtable.model.ClassAmountRecord
import com.sevennotes.classtable.model.ClassRecord
import com.sevennotes.classtable.utils.ExcelUtil.toLocalDate
import org.apache.poi.ss.usermodel.Workbook
import org.apache.poi.ss.usermodel.WorkbookFactory
import java.io.File
import java.time.LocalDate
import java.time.ZoneId
import java.util.Date

object ExcelUtil {

  fun Date.toLocalDate(): LocalDate {
    return this.toInstant().atZone(ZoneId.systemDefault()).toLocalDate()
  }

  fun writeClassRecordToFile(
    context: Context,
    file: File,
    recordList: List<ClassRecord>,
    amountList: List<ClassAmountRecord>
  ): Boolean {
    return try {
      val workbook = createWorkbook(context, recordList, amountList)
      val outputStream = file.outputStream()
      workbook.write(outputStream)
      outputStream.flush()
      outputStream.close()
      true
    } catch (e: Exception) {
      e.printStackTrace()
      false
    }
  }

  fun writeClassRecordToFile(
    context: Context,
    uri: Uri,
    recordList: List<ClassRecord>,
    amountList: List<ClassAmountRecord>
  ): Boolean {
    return try {
      val workbook = createWorkbook(context, recordList, amountList)
      context.contentResolver.openOutputStream(uri)?.use { outputStream ->
        workbook.write(outputStream)
      }
      true
    } catch (e: Exception) {
      e.printStackTrace()
      false
    }
  }

  private fun createWorkbook(
    context: Context,
    recordList: List<ClassRecord>,
    amountList: List<ClassAmountRecord>
  ): Workbook {
    val workbook = WorkbookFactory.create(true)
    val sheet = workbook.createSheet("历史记录")
    val titleRow = sheet.createRow(0)
    titleRow.createCell(0).setCellValue("上课日期")
    titleRow.createCell(1).setCellValue("剩余课时")
    //总课时量的一个记录
    var total = 0
    val amountIter = amountList.iterator()
    var lastAmount: ClassAmountRecord? = null
    if (amountIter.hasNext()) lastAmount = amountIter.next()
    recordList.forEachIndexed { index, classRecord ->
      if (lastAmount != null) {
        if (classRecord.startTime.toLocalDate() >= lastAmount!!.date.toLocalDate()) {
          //说明上课日期比缴费日期靠后，那么总课时量就应该续上了
          total += lastAmount!!.amountChange
          lastAmount = if (amountIter.hasNext()) {
            amountIter.next()
          } else {
            null
          }
        }
      }
      total -= 1
      val row = sheet.createRow(index + 1)
      row.createCell(0).setCellValue(TimeUtil.formatDate(classRecord.startTime, "yyyy年MM月dd日 HH:mm"))
      row.createCell(1).setCellValue("$total 节")
    }

    val sheet2 = workbook.createSheet("缴费记录")
    val titleRow2 = sheet2.createRow(0)
    titleRow2.createCell(0).setCellValue("缴费日期")
    titleRow2.createCell(1).setCellValue("缴费课时")
    amountList.forEachIndexed { index, classAmountRecord ->
      val row = sheet2.createRow(index + 1)
      row.createCell(0).setCellValue(TimeUtil.formatDate(classAmountRecord.date))
      row.createCell(1).setCellValue("${classAmountRecord.amountChange} 节")
    }

    sheet.setColumnWidth(0, 7000)
    sheet2.setColumnWidth(0, 4000)
    return workbook
  }

}